package net.esj.basic.core.engine.config;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

import javax.annotation.PostConstruct;

import net.esj.basic.exception.MelonException;
import net.esj.basic.utils.GetClassLoader;

import org.apache.log4j.Logger;

/**
 * 从properties文件中读取配置
 * @author Administrator
 *
 */
public class PropertiesConfiguration extends AbstractConfiguration {

	protected static final Logger logger = Logger.getLogger(PropertiesConfiguration.class);
	
	private Properties properties;
	private String[] locations;
	
	public void setLocations(String[] locations) {
		this.locations = locations;
		for(String name : locations){
			name = name.replaceAll("\\.", "/");
			URL propertiesUrl = GetClassLoader.fromContext().getResource(name + ".properties");
			if (propertiesUrl == null) {
				logger.debug(name + ".properties missing");
				return;
			}
			load(propertiesUrl);
		}
	}

	private void load(URL propertiesUrl){
		if(properties == null){
			properties = new Properties();
		}
		InputStream in = null;
		try {
			in = propertiesUrl.openStream();
			properties.load(in);
		} catch (IOException e) {
			throw new MelonException("Could not load " + propertiesUrl.getPath() + ".properties:"
					+ e, e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException io) {
					logger.warn("Unable to close input stream", io);
				}
			}
		}
	}

	@Override
	protected String doGetProperty(String key) {
		Object o = properties.get(key);
		if(o!=null){
			return o.toString();
		}
		return null;
	}

	@PostConstruct
	public void init(){
		MelonConfig.registryConfiguration(this);
	}
}
